package vip.ola.pay.channel.chargewx;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.ola.core.common.util.MyLog;
import vip.ola.core.common.util.PayDigestUtil;
import vip.ola.core.entity.PayOrder;
import vip.ola.core.entity.PayPassageAccount;
import vip.ola.pay.ctrl.common.BaseController;
import vip.ola.pay.mq.BaseNotify4MchPay;
import vip.ola.pay.service.RpcCommonService;

import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_COMPLETE;
import static vip.ola.core.common.constant.PayConstant.PAY_STATUS_SUCCESS;

@RequestMapping("/api/chargewx")
@Controller
public class ChargewxPayController extends BaseController {

    private static final MyLog _log = MyLog.getLog(ChargewxPayController.class);

    @Autowired
    private RpcCommonService rpcCommonService;
    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    @PostMapping("/notify")
    @ResponseBody
    public String notify(@RequestParam Map<String,String> map){
        _log.info("接收ChargewxPay回调：" + map.toString());
        String payOrderId = map.get("orderNo");
        PayOrder payOrder = rpcCommonService.rpcPayOrderService.findByPayOrderId(payOrderId);
        Long orderMoney = new BigDecimal(map.get("money")).longValue();
        if (orderMoney.longValue() != payOrder.getAmount()/100){
            return "money fail";
        }
        if(payOrder == null){
            return "order not exist!";
        }
        if (payOrder.getStatus() == PAY_STATUS_SUCCESS || payOrder.getStatus() == PAY_STATUS_COMPLETE) {
            return "success";
        }
        PayPassageAccount payPassageAccount = rpcCommonService.rpcPayPassageAccountService.findById(payOrder.getPassageAccountId());
        if(payPassageAccount == null || StringUtils.isBlank(payPassageAccount.getParam())){
            return "fail";
        }
        String retSign = map.get("sign");
        String sign =getSign(map, payPassageAccount.getPrivateKey());
        _log.info("加签信息：map-{},sign->{}", map, sign );
        if (retSign.equals(sign)){
            if ("success".equals(map.get("status"))){
                int result = rpcCommonService.rpcPayOrderService.updateStatus4Success(payOrder.getPayOrderId());
                _log.info("更新订单状态为支付成功: result={}", result);
                if(result == 1){
                    // 通知业务系统
                    baseNotify4MchPay.doNotify(payOrder, true);
                    return "success";
                }
            }

        }
        return "fail!";
    }



    public static String getSign(Map<String,String> param, String signKey){
        SortedMap<String,String> map = new TreeMap<>(param);
        String str = "";
        map.remove("sign");
        for (Map.Entry<String,String> entry : map.entrySet()){
            if (entry.getValue() == null || "".equals(entry.getValue()) || "sign".equals(entry.getKey()))continue;
            str += entry.getValue();
        }
        return PayDigestUtil.md5(str+signKey,"UTF-8");
    }
}
